﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MyUnityLib.ClassExtension;
using MyUnityLib.Tool;
using UnityEngine.UI;
using System;

namespace ProductExpirationAssistant
{
    public class MainFace : MonoBehaviour
    {
        private InputField m_TodayDate;

        /// <summary>
        /// 初始化
        /// </summary>
        public void Awake()
        {
            m_TodayDate = transform.FindComponentByPath<InputField>("Today/Date");
            m_TodayDate.onEndEdit.AddListener(OnTodayDateEndEdit);
            m_TodayDate.text = DataManager.ins.curDate.ToString("yyyy.MM.dd");
            UITool.BindButtonEvent(transform, "Today/ResetBtn", ResetDateBtn);

            transform.FindComponentByPath<ToggleGroupData>("Bar").onStateChanged.AddListener(OnBarChanged);
        }

        private void OnTodayDateEndEdit(string str)
        {
            if (DateTime.TryParse(m_TodayDate.text.Replace(" ", ""), out DateTime date))
            {
                if (date == DataManager.ins.curDate)
                {
                }
                else
                {
                    DataManager.ins.curDate = date;

                    Messenger.Broadcast(EventName.TodayDateChanged);
                }
                m_TodayDate.text = DataManager.ins.curDate.ToString("yyyy.MM.dd");
            }
            else
            {
                Messenger.Broadcast<TipPopupPanel.Kind, string>(EventName.ShowTipPopup, TipPopupPanel.Kind.Yes, $"[{m_TodayDate.text}] 格式不正确");
                m_TodayDate.text = DataManager.ins.curDate.ToString("yyyy.MM.dd");
            }
        }

        private void ResetDateBtn(Button button)
        {
            var old = DataManager.ins.curDate;
            DataManager.ins.ResetCurDate();
            if (old != DataManager.ins.curDate)
            {
                m_TodayDate.text = DataManager.ins.curDate.ToString("yyyy.MM.dd");

                Messenger.Broadcast(EventName.TodayDateChanged);
            }
        }

        private void OnBarChanged(FunctionType type)
        {
            DataManager.ins.functionType = type;
            Messenger.Broadcast(EventName.FunctionChanged);
        }
    }
}